package org.example.blog.controller;


import org.example.blog.model.BlogInfo;
import org.example.blog.model.Result;
import org.example.blog.service.BlogService;
import org.example.blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RequestMapping("/blog")
@RestController
public class BlogController {

    @Autowired
    private BlogService blogService;
    /**
     * 获取博客列表
     * @return
     */
    @RequestMapping("/getList")
    public List<BlogInfo> getBlogList() {
        return blogService.getBlogList();
    }

    /**
     * 获取博客详情
     * @return
     */
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request) {
        BlogInfo blogInfo =  blogService.getBlogDetail(blogId);
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId != null && blogInfo.getUserId() == userId) {
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }

    /**
     * 发布博客
     */

    @RequestMapping("/add")
    public Result publishBlog(String title, String content, HttpServletRequest request) {
        //发布博客 需要知道 谁写的 也就是userId
        //还有标题以及发布内容
        //从token中获取userId
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId == null || userId < 0) {
            return Result.fail("用户未登录", false);
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setUserId(userId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.addBlog(blogInfo);
        return Result.success(true);
    }

    /**
     * 编辑博客
     */
    @RequestMapping("/update")
    public boolean updateBlog(Integer id, String title, String content) {
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        // 根据博客id去更新数据
        blogInfo.setId(id);
        blogService.updateBlog(blogInfo);
        return true;
    }
    /**
     * 删除博客
     */
    @RequestMapping("/delete")
    public boolean deleteBlog(Integer blogId) {
        blogService.deleteBlog(blogId);
        return true;
    }
}
